/*
 * Copyright (C) 2018,米珈科技有限公司 All rights reserved.
 * Project：baixingshenghuo
 * Author：马靖乘
 * Date：3/22/19 4:53 PM
 */
import 'dart:convert';

import 'package:baixing/model/category_goods_list.dart';
import 'package:baixing/provide/category_goods_provide.dart';
import 'package:baixing/provide/child_category.dart';
import 'package:baixing/service/service_method.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provide/provide.dart';

//商品列表，可以上拉加载的效果
class CategoryGoods extends StatefulWidget {
  @override
  _CategoryGoodsState createState() => _CategoryGoodsState();
}

class _CategoryGoodsState extends State<CategoryGoods> {
  GlobalKey<RefreshFooterState> _footerKey =
  new GlobalKey<RefreshFooterState>();

  var scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Provide<CategoryGoodsProvide>(builder: (context, child, data) {
      try {
        if (Provide
            .value<ChildCategory>(context)
            .page == 1) {
          //需要把列表位置放到最上边
          scrollController.jumpTo(0.0);
        }
      } catch (e) {
        print("进入页面第一次初始化：$e");
      }
      return Expanded(
          child: Container(
            width: ScreenUtil().setWidth(570),
            child: _showView(data.list),
          ));
    });
  }

  Widget _showView(List list) {
    if (list.length != 0) {
      return Scaffold(
          body: EasyRefresh(
            refreshFooter: ClassicsFooter(
              key: _footerKey,
              bgColor: Colors.white,
              textColor: Colors.pink,
              moreInfoColor: Colors.pink,
              showMore: true,
              noMoreText: Provide
                  .value<ChildCategory>(context)
                  .noMoreText,
              moreInfo: "加载中……",
              loadReadyText: "上拉加载……",
            ),
            child: ListView.builder(
              controller: scrollController,
              itemCount: list.length,
              itemBuilder: (context, index) {
                return _listItemWidget(list, index);
              },
            ),
            loadMore: () async {
              print("开始加载更多……");
              _getMoreList();
            },
            onRefresh: () {
              print("开始下拉刷新……");
            },
          ));
    } else {
      return Center(
        child: Text("暂无数据"),
      );
    }
  }

  void _getMoreList() async {
    Provide.value<ChildCategory>(context).addPage();
    var data = {
      "categoryId": Provide
          .value<ChildCategory>(context)
          .categoryId,
      "categorySubId": Provide
          .value<ChildCategory>(context)
          .subId,
      "page": Provide
          .value<ChildCategory>(context)
          .page,
    };
    await request("getMallGoods", formData: data).then((onValue) {
      var data = json.decode(onValue.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      if (goodsList.data == null) {
        Fluttertoast.showToast(
            msg: "没有更多数据了",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            backgroundColor: Colors.pink,
            textColor: Colors.white,
            fontSize: 16
        );
        Provide.value<ChildCategory>(context).changeNoMore("没有更多数据了");
      } else {
        Provide.value<CategoryGoodsProvide>(context)
            .getMoreList(goodsList.data);
      }
    });
  }

  Widget _goodsImage(List newList, index) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(newList[index].image),
    );
  }

  Widget _goodsName(List newList, index) {
    return Container(
        width: ScreenUtil().setWidth(370),
        padding: EdgeInsets.all(5),
        child: Text(
          newList[index].goodsName,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ));
  }

  Widget _goodsPrice(List newList, index) {
    return Container(
      margin: EdgeInsets.only(top: 20),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text(
            "价格：￥${newList[index].presentPrice}",
            style:
            TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            "￥${newList[index].oriPrice}",
            style: TextStyle(
                color: Colors.black26, decoration: TextDecoration.lineThrough),
          ),
        ],
      ),
    );
  }

  Widget _listItemWidget(List newList, index) {
    return InkWell(
      onTap: () {},
      child: Container(
        padding: EdgeInsets.only(top: 5, bottom: 5),
        height: ScreenUtil().setHeight(210),
        width: ScreenUtil().setWidth(570),
        child: Row(
          children: <Widget>[
            _goodsImage(newList, index),
            Column(
              children: <Widget>[
                _goodsName(newList, index),
                _goodsPrice(newList, index),
              ],
            )
          ],
        ),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                bottom: BorderSide(
                  width: 1,
                  color: Colors.black26,
                ))),
      ),
    );
  }
}
